//传送阵
#include <iostream>
#include <vector>
using namespace std;
int n;
vector<int> nums;
vector<int> vis; //判断这个传送阵是在哪个环中，下标表示的是传送阵编号
vector<int> cnt;	//判断每个环中传送阵的个数

int main()
{
	cin >> n;
	nums.resize(n + 1);
	vis.resize(n + 1);
	cnt.resize(n + 1);
	for (size_t i = 1; i <= n; ++i)
		cin >> nums[i];
	int index = 1;//环的编号
	for (size_t i = 1; i <= n; ++i)
	{
		if (vis[i] == 0)
		{
			//以i位置传送阵开始走出一个环
			vis[i] = index;
			cnt[index]++;
			int temp = i;
			while (nums[temp] != i)
			{
				temp = nums[temp];
				vis[temp] = index;
				cnt[index]++;
			}
			++index;
		}
	}
	//使用魔法，可以让两个环相连，返回相连形成大环的最大值
	int ret = 0;
	for(size_t i = 2 ; i <= n ; ++i)
	{
		//若两个环不是同一个环，就形成大环，最后保存最大的大环中元素的个数
		if (vis[i] != vis[i - 1])
			ret = max(ret, cnt[vis[i]] + cnt[vis[i - 1]]);
	}
	cout << ret;
	return 0;
}

//查找总价格为目标值的两个商品
class Solution {
public:
    vector<int> twoSum(vector<int>& price, int target) {
        int left = 0 , right = price.size()-1;
        vector<int> ret(2);
        while(left < right)
        {
            int sum = price[left] + price[right];
            if(sum > target) right--;
            else if(sum < target) left++;
            else
            {
                ret[0] = price[left] , ret[1] = price[right];
                break;
            }
        }
        return ret;
    }
};

//三数之和
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ret;
        int n = nums.size();
        sort(nums.begin(),nums.end());
        for(auto& x : nums) cout << x << " ";
        cout << endl;
        for(int i = n-1 ; i >= 2 ;)
        {
            int left = 0 , right = i-1;
            while(left < right)
            {
                int sum = nums[i] + nums[left] + nums[right];
                if(sum > 0) --right;
                else if(sum < 0) ++left;
                else 
                {
                    ret.push_back({nums[i],nums[left],nums[right]});
                    --right;
                    ++left;
                    while(left < right && nums[right+1] == nums[right]) --right;
                    while(left < right && nums[left-1] == nums[left]) ++left;
                }
            }
                --i;
            while(i >= 0 && nums[i+1] == nums[i]) --i;
        }
        return ret;
    }
};